﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Management;

namespace MonitorServersWeb
{
   public static class WMIUtil
    {
        private static ManagementObjectSearcher ExecQuery(ServerInfo ServerInfo, string Query)
        {
            try
            {
                ConnectionOptions connection;
                if (ServerInfo.userName == "")
                { connection = new ConnectionOptions(); }
                else
                {
                    connection = new ConnectionOptions();
                    connection.Username = ServerInfo.userName;
                    connection.Password = ServerInfo.passWord;
                    //connection.Authority = "ntlmdomain:DOMAIN";
                }
                ManagementScope scope = new ManagementScope(
                    string.Format("\\\\{0}\\root\\CIMV2", ServerInfo.serverName), connection);
                scope.Connect();


                ObjectQuery query = new ObjectQuery(Query);

                ManagementObjectSearcher searcher =
                    new ManagementObjectSearcher(scope, query);

                return searcher;
            }

            catch (Exception ex)
            {
                return null;
            }
          
        }

        ///////////////////////////////////////////////////////////////////////////////////////////////

        public static List<ServerDisks> GetDiskSpace(ServerInfo serverInfo)
        {
            List<ServerDisks> disks = new List<ServerDisks>();
            try
            {
                string query = "SELECT Name,Status,Size,FreeSpace FROM Win32_LogicalDisk";

                ManagementObjectSearcher searcher = ExecQuery(serverInfo, query);
                
                ServerDisks disk;
                if (searcher == null)
                {
                    return null;
                }
                    foreach (ManagementObject queryObj in searcher.Get())
                    {
                        disk = new ServerDisks();
                        disk.DiskName = (queryObj["Name"] != null ? queryObj["Name"].ToString() : "");
                        disk.Status = (queryObj["Status"] != null ? queryObj["Status"].ToString() : "");
                        disk.TotalSpace = Int64.Parse((queryObj["Size"] != null ? queryObj["Size"].ToString() : "0"));
                        disk.FreeSpace = Int64.Parse((queryObj["Size"] != null ? queryObj["FreeSpace"].ToString() : "0"));

                        disks.Add(disk);
                    }
                
            }
            catch (ManagementException e)
            {
                //
            }
            catch (Exception ex)
            {
                return null;
            }
            return disks;
        }



        public static List<ServerServices> GetServices(ServerInfo ServerName)
        {
            List<ServerServices> services = new List<ServerServices>();
            try
            {
                string query = string.Format("SELECT DisplayName,State,StartMode FROM Win32_Service WHERE DisplayName like '%{0}%' or DisplayName like '%{1}%'' ", "SQL", "SHAREPOINT");

                ManagementObjectSearcher searcher = ExecQuery(ServerName, query);

                ServerServices service;
                if (searcher.Scope.IsConnected)
                {
                    foreach (ManagementObject queryObj in searcher.Get())
                    {
                        service = new ServerServices();
                        service.ServiceName = (queryObj["DisplayName"] != null ? queryObj["DisplayName"].ToString() : "");
                        service.Status = (queryObj["State"] != null ? queryObj["State"].ToString() : "");
                        service.StartMode = (queryObj["StartMode"] != null ? queryObj["StartMode"].ToString() : "");
                        services.Add(service);
                    }
                }
                else
                { return null; }
               
            }
            catch (ManagementException e)
            {
                //
            }
            catch (Exception ex)
            {
                return null;
            }
            return services;
        }



        public static List<ServerMemory> GetServerMemory(ServerInfo ServerName)
        {
            List<ServerMemory> info = new List<ServerMemory>();
            try
            {
                string query = "SELECT FreePhysicalMemory,TotalVisibleMemorySize FROM Win32_OperatingSystem";

                ManagementObjectSearcher searcher = ExecQuery(ServerName, query);

                ServerMemory service;
                if (searcher.Scope.IsConnected)
                {
                    foreach (ManagementObject queryObj in searcher.Get())
                    {
                        service = new ServerMemory();
                        service.FreePhysicalMemory = (queryObj["FreePhysicalMemory"] != null ? Int64.Parse(queryObj["FreePhysicalMemory"].ToString()) : 0);
                        service.TotalVisibleMemorySize = (queryObj["TotalVisibleMemorySize"] != null ? Int64.Parse(queryObj["TotalVisibleMemorySize"].ToString()) : 0);

                        //if (service.ServiceName.Contains("Ventyx") || service.ServiceName.Contains("SQL"))
                        {
                            info.Add(service);
                        }
                    }
                }
                else
                { return null; }
                
            }
            catch (ManagementException e)
            {
                //
            }
            catch (Exception ex)
            {
                return null;
            }
            return info;
        }

        public static List<ServerCPU> GetServerCPU(ServerInfo ServerName)
        {
            List<ServerCPU> info = new List<ServerCPU>();
            try
            {
                string query = "SELECT LoadPercentage FROM Win32_OperatingSystem";

                ManagementObjectSearcher searcher = ExecQuery(ServerName, query);

                ServerCPU service;
                if (searcher.Scope.IsConnected)
                {
                    foreach (ManagementObject queryObj in searcher.Get())
                    {
                        service = new ServerCPU();
                        service.CPULoadPercentage = (queryObj["LoadPercentage"] != null ? Int64.Parse(queryObj["LoadPercentage"].ToString()) : 0);
                        info.Add(service);
                    }
                }
                else
                { return null; }
            }
            catch (ManagementException e)
            {
                //
            }
            catch (Exception ex)
            {
                return info;
            }
            return info;
        }


        public static List<MessageQueue> GetMessageQueues(ServerInfo ServerName)
        {
            List<MessageQueue> info = new List<MessageQueue>();
            try
            {
                string query = "Select Name,MessagesInQueue From Win32_PerfRawData_MSMQ_MSMQQueue where MessagesInQueue > 0";

                ManagementObjectSearcher searcher = ExecQuery(ServerName, query);

                MessageQueue service;
                if (searcher.Scope.IsConnected)
                {
                    foreach (ManagementObject queryObj in searcher.Get())
                    {
                        service = new MessageQueue();
                        service.QueueName = (queryObj["Name"] != null ? queryObj["Name"].ToString() : "");
                        service.NumberOfMessages = (queryObj["MessagesInQueue"] != null ? int.Parse(queryObj["MessagesInQueue"].ToString()) : 0);

                        info.Add(service);

                    }
                }
                else { return null; }
            }
            catch (ManagementException e)
            {
                //
            }
            catch (Exception ex)
            {
                return null;
            }
            return info;
        }

        ///////////////////////////////////////////////////////////////////////////////////////////////


    }
}